<template>
  <!-- 投资项目详情 -->
  <div class="tobeDone">
      <public-search
          :fields="fields"
          :search-param="form"
          @on-query="onQuery"
          @on-reset="onReset"
      />
      <public-table
              ref="publicTableRef"
              index
              :selection="false"
              :indexWidth="'100'"
              :page="page"
              :tableData="tableData"
              :tableOption.sync="tableOption"
              @page-change="onPageChange"
      >
          <template #buttons="scope">
           <div>
               <el-button style="margin-left: 0 !important;" class="button_funtion2 m-b5 m-r10" @click="taskManagement(scope.row,'2')">任务执行管理</el-button>
               <el-button style="margin-left: 0 !important;" class="button_funtion2 m-b5 m-r10" @click="planOptionHandel(scope.row)">投资计划</el-button>
<!--               <el-button style="margin-left: 0 !important;" class="m-b5 m-r10" @click="taskManagement(scope.row,'1')">任务管理</el-button>-->
               <el-button style="margin-left: 0 !important;" class="button_funtion2 m-b5 m-r10" @click="approvalOptionHandel(scope.row)">立项变更</el-button>
               <el-button style="margin-left: 0 !important;" class="button_funtion2 m-b5 m-r10" @click="flowOptionHandel(scope.row)">现金流量表</el-button>
               <el-button style="margin-left: 0 !important;" class="button_edit m-b5" @click="viewOptionHandel(scope.row)">查看</el-button>
               <el-button
                       style="margin-left: 0 !important;"
                       class="button_funtion2 m-b5"
                       v-if="scope.row.projectNature===1 || scope.row.projectNature===3"
                       @click="natureChange(scope.row)"
               >性质变更</el-button>
           </div>
          </template>
      </public-table>
  </div>
</template>

<script setup>
import {department, fundApi} from '@/api/project'
import {onMounted, reactive, ref} from 'vue'
import { useRouter } from 'vue-router'
import PublicTable from "@/components/PublicTable";
import PublicSearch from "@/components/PublicSearch";
import {tableCommonFun} from "@/hooks/tableCommon";
import {otherApi, reserveInvestmentProjectLibraryApi} from "@/api/investment";
import {ElMessage, ElMessageBox} from "element-plus";


const router = useRouter();

const interfaceConfig = reactive({
    fileName:'investment',
    apiPath:'reserveInvestmentProjectLibraryApi.getPage',
});

const exportConfig = reactive({
    fileName:'investment',
    apiPath:'projectSetApi.exportProjectSet',
    tableName:'项目集表'
});

/**
 * 默认参数
 * @type {UnwrapNestedRefs<{prepareStatus: number}>}
 */
const defaultParameters = reactive({
    prepareStatus: 1
});

const {
    form,
    page,
    tableOption,
    tableData,
    onQuery,
    onReset,
    onPageChange,
    getData,
    onExport
}  = tableCommonFun(interfaceConfig,exportConfig,defaultParameters);

const fields = ref([
    {   type:'input',
        label:'项目名称',
        key:'keyword',
        placeholder:'请输入项目名称',
        clearable:true
    },
    {   type:'datetimerange',
        label:'创建时间',
        key:'valueTime',
        startTimeName:'startTime',
        endTimeName:'endTime',
        placeholder:'请选择创建时间',
        clearable:true,
        fun:(e,params)=>{
            if(e && e instanceof Array && e.length>0){
                form.value[params.startTimeName] = e[0];
                form.value[params.endTimeName] = e[1];
            }
            if(!e || (e instanceof  Array && e.length===0)){
                form.value[params.startTimeName] = '';
                form.value[params.endTimeName] = '';
            }
        }
    },
    {   type:'select',
        label:'项目类型',
        key:'projectTypeId',
        placeholder:'请选择项目类型',
        clearable:true,
        options:{
            labelKey:'enumName',
            valueKey:'enumId',
            list:[]
        }
    },
    {   type:'select',
        label:'项目部门',
        key:'departmentId',
        placeholder:'请选择项目部门',
        clearable:true,
        options:{
            labelKey:'departmentName',
            valueKey:'departmentId',
            list:[]
        },
        fun:(e)=>{
            getLeaderByDepartmentId(e);
        }
    },
    {   type:'select',
        label:'发起人',
        key:'responsibleUserId',
        placeholder:'请选择发起人',
        clearable:true,
        options:{
            labelKey:'userName',
            valueKey:'userId',
            list:[]
        }
    },
]);

tableOption.value = [
  { label: "项目名称", prop: "projectName", minWidth: 100 },
  { label: "项目类型", prop: "projectTypeName", minWidth: 100 },
  { label: "归属资产/业态", prop: "industryTypeName", minWidth: 130 },
  {
    label: "项目性质", prop: "projectNature", formatter: (val) => {
      return ['-', '新建项目', '续建项目', '新设立', '续投'][val] || '-';
    }, minWidth: 100
  },
  { label: "发起人", prop: "responsibleUserName", minWidth: 100 },
  { label: "项目总投（万）", prop: "projectAmount", minWidth: 120,formatter: (val) => {
         if(val && typeof val === 'number'){
            return (val/10000).toFixed(2);
         }
         return '-';
      }},
  { label: "创建时间", prop: "createTime", minWidth: 150 },
  { label: "创建人", prop: "createUserName", minWidth: 100 },
  /*  { label: "项目状态", prop: "projectStatus",formatter:(val)=>{
            return ['未开始','进行中','已超期','已完成','异常终止'][val] || '-';
        } },*/
  {
    label: '操作',
    slot: true,
    width: 400,
    overHidden: false,
    slotName: 'buttons',
      fixed: "right"
  },
];

/**
 * 获取下拉框
 */
const getListEnum = (type) => {
    otherApi.getListEnum({type: type}).then(res=>{
        const {code,data} = res;
        if(code == 200){
            fields.value[2].options.list = data;
        }
    });
}

/**
 * 获取所有部门
 */
const getAllDepartments = () => {
    department.getAllDepartments().then((res) => {
        const { code, data, msg } = res;
        if (code == 200) {
            fields.value[3].options.list = data;
        }
    });
};

/**
 * 根据部门id查负责人
 * @param responsibleDepartmentId
 */
const getLeaderByDepartmentId = (responsibleDepartmentId) => {
    department.getLeaderByDepartmentId(responsibleDepartmentId).then((res) => {
        const { code, data, msg } = res;
        if (code == 200) {
            fields.value[4].options.list = data;
        }
    });
};

// 投资计划
const planOptionHandel = (row) => {
  router.push({
    path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/preparationOfInvestmentPlan/${row.projectId}`
  })
}

/**
 * 跳转任务执行管理
 * @param row
 * @param type
 */
const taskManagement = (row,type) => {
    switch (type) {
        case '1': // 任务管理
            router.push({ path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/taskManagement/${row.projectId}` });
            break;
        case '2': // 任务执行管理
            router.push({ path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/taskExecutionManagement/${row.projectId}` });
            break;
    }
}

// 立项变更
const approvalOptionHandel = (row) => {
    router.push({
    path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/projectApprovalChange/${row.projectId}/${row.projectTypeId}`,
  })
}

// 现金流量表
const flowOptionHandel = (row) => {
    router.push({
    path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/cashFlowStatement/${row.projectId}/${row.projectName}`,
  })
}

// 查看
const viewOptionHandel = (row) => {
    router.push({
    path: `/investmentProjectManagement/investmentProjects/investmentProjectInformation/investmentProjectDetails/${row.projectId}/${row.projectTypeId}/${row.partnerName}`
  })
}

/**
 * 项目变更
 */
const natureChange = (row) => {
    ElMessageBox.confirm(
        '确认变更项目性质吗?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then((action) => {
          if(action==='confirm'){
              reserveInvestmentProjectLibraryApi.natureChange({projectId:row.projectId}).then(res=>{
                if(res.code==='200'){
                    ElMessage.success('变更成功!');
                    onQuery();
                }
              })
          }
        })
}

onMounted(()=>{
    getListEnum(1);
    getAllDepartments();
    getData({
        pageNum:1,
        pageSize:10,
        param:{
            prepareStatus:1
        }
    });
})
</script>

<style lang="scss" scoped>
.tobeDone {
  width: 100%;
  height: 100%;
}
</style>
